/**
 * Project 68th
 */


#ifndef _TCPCONNECTION_H
#define _TCPCONNECTION_H

#include "Socket.h"
#include "InetAddress.h"
#include "SocketIO.h"
#include <string>
#include <memory>
#include <functional>
#include <cstring>
#include <stdexcept>
#include "Message.h"

using std::string;
using std::shared_ptr;
using std::function;

class TcpConnection;
class EventLoop;

using TcpConnectionPtr = shared_ptr<TcpConnection>;
using TcpConnectionCallback = function<void(const TcpConnectionPtr &)>;

class TcpConnection 
: public std::enable_shared_from_this<TcpConnection>
{
public: 

    /**
     * @param fd
     */
    TcpConnection(int fd, EventLoop * loop);

    ~TcpConnection();

    Message receive();

    /**
     * @param msg
     */
    void send(const Message & msg);
    
    void sendInLoop(const Message & msg);

    //将本端的地址信息与对端的地址信息串联
    string toString();

    bool isClosed();

    void setNewConnectionCallback(const TcpConnectionCallback & cb);
    void setMessageCallback(const TcpConnectionCallback & cb);
    void setCloseCallback(const TcpConnectionCallback & cb);

    void handleNewConnectionCallback();
    void handleMessageCallback();
    void handleCloseCallback();
private: 
    //获取当前这条连接的本端地址信息与对端地址信息
    InetAddress getLocalAddr();
    InetAddress getPeerAddr();

private:
    EventLoop* _loop;

    SocketIO _sockIO;
    Socket _sock;
    InetAddress _localAddr;
    InetAddress _peerAddr;

    TcpConnectionCallback _onNewConnection;
    TcpConnectionCallback _onMessage;
    TcpConnectionCallback _onClose;
};

#endif //_TCPCONNECTION_H
